package org.cvcsc.weproject.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.cvcsc.weproject.domain.Student;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JwtUtil {
    // Replace the existing key with a secure one
    private final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); // Generates a 256-bit key
    private final long jwtExpiration = 86400000L; // 24 hours

    public String generateToken(Student student) {
        return Jwts.builder()
                .setSubject(student.getId().toString())
                .claim("name", student.getStudentNameAndNumber().getName())
                .claim("isAdmin", student.isAdmin())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
                .signWith(key) // Use the secure key
                .compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key) // Use the secure key
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}